package com.cy.ppj.service.account.impl;

import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.dao.mapper.account.CommissionMapper;
import com.cy.ppj.dao.mapper.account.CommissionRecordMapper;
import com.cy.ppj.dao.mapper.order.OrderMapper;
import com.cy.ppj.dao.mapper.user.UserRecommenderMapper;
import com.cy.ppj.model.domian.account.Commission;
import com.cy.ppj.model.domian.order.CommissionRecord;
import com.cy.ppj.model.dto.commission.CommissionDTO;
import com.cy.ppj.model.dto.order.OrderDealRecordDTO;
import com.cy.ppj.model.dto.recommender.UserRecommenderDTO;
import com.cy.ppj.model.dto.sys.BrokerCommissionSettingsDTO;
import com.cy.ppj.model.dto.sys.TeamCommissionSettingsDTO;
import com.cy.ppj.model.enums.CommissionType;
import com.cy.ppj.model.enums.DealType;
import com.cy.ppj.model.enums.account.BrokerLevel;
import com.cy.ppj.service.BaseService;
import com.cy.ppj.service.account.CommissionRecordService;
import com.cy.ppj.service.account.CommissionService;
import com.cy.ppj.service.sys.SystemSettingsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @description: 佣金
 * @author: Ocean
 * @create: 2018-08-03 20:09
 **/
@Slf4j
@Service
public class CommissionServiceImpl extends BaseService implements CommissionService {

    @Autowired
    private CommissionRecordMapper commissionRecordMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserRecommenderMapper userRecommenderMapper;
    @Autowired
    private CommissionMapper commissionMapper;
    @Autowired
    private SystemSettingsService systemSettingsService;
    @Autowired
    private CommissionRecordService commissionRecordService;

    @Override
    public Commission queryCommission(Commission commission) {
        return commissionMapper.selectOne(commission);
    }

    @Override
    @Transactional
    public void payCommission1(Long orderId) {

        //更新订单佣金状态
        int result = orderMapper.updateCommissionStatusComplete(orderId);
        state(result == 1, "该订单佣金发放异常");

        //获取订单信息,用于备注
        OrderDealRecordDTO dealRecordDTO = orderMapper.selectOrderDealRecordInfo(orderId);

        //查询佣金信息
        CommissionDTO commissionDTO = commissionRecordMapper.selectCommissionInfo(orderId);
        state(commissionDTO != null, "数据异常");
        state(commissionDTO.getBrokerLevel() != null, "该用户未成为经纪人");

        Date time = new Date();

        //计算佣金
        BigDecimal brokerRate = commissionDTO.getBrokerRate();
        BigDecimal amount = CommonUtils.multiplyWithPercent(commissionDTO.getLoanAmount(), commissionDTO.getCommissionRate());
        amount = CommonUtils.multiplyWithPercent(amount, brokerRate);

        //佣金记录
        CommissionRecord commissionRecord = new CommissionRecord();
        BeanUtils.copyProperties(commissionDTO, commissionRecord);
        commissionRecord.setAmount(amount);
        commissionRecord.setCreateTime(time);
        commissionRecord.setRemarkObject(dealRecordDTO);
        if (commissionDTO.getCollectCommission()) {
            //当统一管理佣金时
            boolean flag = commissionDTO.getDirectorId() != null && commissionDTO.getDirectorId() > 0;
            state(flag, "公司统一管理佣金但未设置管理员");
            //用户没有交易类型，不做交易记录
            commissionRecord.setType(CommissionType.BORKER_COMPANY);

            //公司管理员佣金记录
            CommissionRecord companyCommissionRecord = new CommissionRecord();
            companyCommissionRecord.setCompanyId(commissionDTO.getCompanyId());
            companyCommissionRecord.setType(CommissionType.COMPANY);
            companyCommissionRecord.setAmount(amount);
            companyCommissionRecord.setOrderId(orderId);
            companyCommissionRecord.setUserId(commissionDTO.getDirectorId());
            companyCommissionRecord.setCreateTime(time);
            companyCommissionRecord.setDealType(DealType.COMPANY_COMMISSION);
            companyCommissionRecord.setRemarkObject(dealRecordDTO);
            commissionRecordService.addComissionRecord(companyCommissionRecord);

        } else {
            //经纪人佣金记录
            commissionRecord.setDealType(DealType.COMMISSION);
            commissionRecord.setType(CommissionType.BORKER_USER);
        }
        commissionRecordService.addComissionRecord(commissionRecord);

        //团队返佣，交易记录, 佣金记录
        //查找推荐人，3级关系
        UserRecommenderDTO userRecommenderDTO = userRecommenderMapper.selectRecommenderRelation(commissionDTO.getUserId());
        if (userRecommenderDTO == null) {
            return;
        }

        //团队返佣设置
        TeamCommissionSettingsDTO teamCommissionSettings = systemSettingsService.queryTeamCommissionSettingsInCache();
        state(teamCommissionSettings != null, "团队返佣设置异常");

        //计算一级返佣
        BigDecimal firstCommission = CommonUtils.multiplyWithPercent(amount, teamCommissionSettings.getFirstRate());
        //一级返佣，佣金记录
        CommissionRecord firstCommissionRecord = new CommissionRecord();
        firstCommissionRecord.setCompanyId(commissionDTO.getCompanyId());
        firstCommissionRecord.setType(CommissionType.TEAM_FIRST);
        firstCommissionRecord.setAmount(firstCommission);
        firstCommissionRecord.setOrderId(orderId);
        firstCommissionRecord.setUserId(userRecommenderDTO.getFirstUserRecommender());
        firstCommissionRecord.setDealType(DealType.TEAM_COMMISSION_FIRST);
        firstCommissionRecord.setTeamUserId(commissionDTO.getUserId());
        firstCommissionRecord.setCreateTime(time);
        firstCommissionRecord.setRemarkObject(dealRecordDTO);
        commissionRecordService.addComissionRecord(firstCommissionRecord);

        if (userRecommenderDTO.getSecondUserRecommender() == null) {
            return;
        }

        //计算二级返佣
        BigDecimal secondCommission = CommonUtils.multiplyWithPercent(amount, teamCommissionSettings.getSecondRate());
        //二级返佣，佣金记录
        CommissionRecord secondCommissionRecord = new CommissionRecord();
        secondCommissionRecord.setType(CommissionType.TEAM_SECOND);
        secondCommissionRecord.setAmount(secondCommission);
        secondCommissionRecord.setOrderId(orderId);
        secondCommissionRecord.setUserId(userRecommenderDTO.getSecondUserRecommender());
        secondCommissionRecord.setCreateTime(time);
        secondCommissionRecord.setDealType(DealType.TEAM_COMMISSION_SECOND);
        secondCommissionRecord.setTeamUserId(commissionDTO.getUserId());
        secondCommissionRecord.setRemarkObject(dealRecordDTO);
        commissionRecordService.addComissionRecord(secondCommissionRecord);

    }

    @Override
    @Transactional
    public void payCommission2(Long orderId) {

        Date time = new Date();
        //更新订单佣金状态
        int result = orderMapper.updateCommissionStatusComplete(orderId);
        state(result == 1, "该订单佣金发放异常");

        //获取订单信息,用于备注
        OrderDealRecordDTO dealRecordDTO = orderMapper.selectOrderDealRecordInfo2(orderId);

        //查询佣金相关信息
        CommissionDTO commissionDTO = commissionRecordMapper.selectCommissionInfo2(orderId);
        state(commissionDTO != null, "数据异常");
        state(commissionDTO.getBrokerLevel() != null, "该用户未成为小精灵");

        //计算佣金
        BigDecimal loanAmount = commissionDTO.getLoanAmount();
        BigDecimal commissionAmount = BigDecimal.ZERO;
        if(BrokerLevel.OFFICIAL.equals(commissionDTO.getBrokerLevel())) {
            //当前用户A是白银小精灵
            //计算白银小精灵的直推佣金
            commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(BrokerLevel.OFFICIAL.getRewardRatio()));
            //白银小精灵的直推佣金记录
            CommissionRecord commissionRecord = new CommissionRecord();
            commissionRecord.setUserId(commissionDTO.getUserId());
            commissionRecord.setOrderId(commissionDTO.getOrderId());
            commissionRecord.setAmount(commissionAmount);
            commissionRecord.setCreateTime(time);
            dealRecordDTO.setCommissionRate(new BigDecimal(BrokerLevel.OFFICIAL.getRewardRatio()));
            commissionRecord.setRemarkObject(dealRecordDTO);
            commissionRecord.setType(CommissionType.BORKER_USER);
            commissionRecord.setDealType(DealType.COMMISSION);
            commissionRecordService.addComissionRecord(commissionRecord);

            //找当前用户A的上级用户B，判断团队返佣
            UserRecommenderDTO firstUserRecommenderDTO = userRecommenderMapper.selectUserRecommenderByUserId(commissionDTO.getUserId());
            if(firstUserRecommenderDTO != null) {
                if(BrokerLevel.GOLDEN.equals(firstUserRecommenderDTO.getLevel())) {
                    //如果上级B是黄金小精灵，则当前订单放款额的0.2%返佣
                    commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(0.20));
                    //黄金团队佣金记录
                    CommissionRecord goldenTeamCommissionRecord = new CommissionRecord();
                    goldenTeamCommissionRecord.setUserId(firstUserRecommenderDTO.getRecommendUserId());
                    goldenTeamCommissionRecord.setOrderId(commissionDTO.getOrderId());
                    goldenTeamCommissionRecord.setAmount(commissionAmount);
                    goldenTeamCommissionRecord.setCreateTime(time);
                    dealRecordDTO.setCommissionRate(new BigDecimal(0.20));
                    dealRecordDTO.setBorkerLevelName("白银会员");
                    goldenTeamCommissionRecord.setRemarkObject(dealRecordDTO);
                    goldenTeamCommissionRecord.setType(CommissionType.TEAM);
                    goldenTeamCommissionRecord.setDealType(DealType.TEAM);
                    goldenTeamCommissionRecord.setTeamUserId(commissionDTO.getUserId());
                    commissionRecordService.addComissionRecord(goldenTeamCommissionRecord);

                }else if(BrokerLevel.DIAMOND.equals(firstUserRecommenderDTO.getLevel())) {
                    //如果上级B是钻石小精灵，则：
                    //1.当前订单放款额的0.7%返佣
                    commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(0.70));
                    //钻石团队佣金记录
                    CommissionRecord diamondTeamCommissionRecord = new CommissionRecord();
                    diamondTeamCommissionRecord.setUserId(firstUserRecommenderDTO.getRecommendUserId());
                    diamondTeamCommissionRecord.setOrderId(commissionDTO.getOrderId());
                    diamondTeamCommissionRecord.setAmount(commissionAmount);
                    diamondTeamCommissionRecord.setCreateTime(time);
                    dealRecordDTO.setCommissionRate(new BigDecimal(0.70));
                    dealRecordDTO.setBorkerLevelName("白银会员");
                    diamondTeamCommissionRecord.setRemarkObject(dealRecordDTO);
                    diamondTeamCommissionRecord.setType(CommissionType.TEAM);
                    diamondTeamCommissionRecord.setDealType(DealType.TEAM);
                    diamondTeamCommissionRecord.setTeamUserId(commissionDTO.getUserId());
                    commissionRecordService.addComissionRecord(diamondTeamCommissionRecord);

                    //2.再找到上级B的上级C
                    UserRecommenderDTO secondUserRecommenderDTO = userRecommenderMapper.selectUserRecommenderByUserId(firstUserRecommenderDTO.getRecommendUserId());
                    if(secondUserRecommenderDTO != null) {
                        if(BrokerLevel.DIAMOND.equals(secondUserRecommenderDTO.getLevel())) {
                            //C如果是钻石，当前订单放款额的0.1%返佣给C，即钻石津贴
                            commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(0.10));
                            //钻石津贴佣金记录
                            CommissionRecord diamondAllowanceCommissionRecord = new CommissionRecord();
                            diamondAllowanceCommissionRecord.setUserId(secondUserRecommenderDTO.getRecommendUserId());
                            diamondAllowanceCommissionRecord.setOrderId(commissionDTO.getOrderId());
                            diamondAllowanceCommissionRecord.setAmount(commissionAmount);
                            diamondAllowanceCommissionRecord.setCreateTime(time);
                            dealRecordDTO.setCommissionRate(new BigDecimal(0.10));
                            dealRecordDTO.setUserRealName(firstUserRecommenderDTO.getRecommendUserRealName());
                            diamondAllowanceCommissionRecord.setRemarkObject(dealRecordDTO);
                            diamondAllowanceCommissionRecord.setType(CommissionType.DIAMOND_ALLOWANCE);
                            diamondAllowanceCommissionRecord.setDealType(DealType.DIAMOND_ALLOWANCE);
                            diamondAllowanceCommissionRecord.setTeamUserId(commissionDTO.getUserId());
                            commissionRecordService.addComissionRecord(diamondAllowanceCommissionRecord);
                        }
                    }
                }
            }
        }else if(BrokerLevel.GOLDEN.equals(commissionDTO.getBrokerLevel())) {
            //当前用户A是黄金小精灵
            //计算黄金小精灵的直推佣金
            commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(BrokerLevel.GOLDEN.getRewardRatio()));
            //黄金小精灵的直推佣金记录
            CommissionRecord commissionRecord = new CommissionRecord();
            commissionRecord.setUserId(commissionDTO.getUserId());
            commissionRecord.setOrderId(commissionDTO.getOrderId());
            commissionRecord.setAmount(commissionAmount);
            commissionRecord.setCreateTime(time);
            dealRecordDTO.setCommissionRate(new BigDecimal(BrokerLevel.GOLDEN.getRewardRatio()));
            commissionRecord.setRemarkObject(dealRecordDTO);
            commissionRecord.setType(CommissionType.BORKER_USER);
            commissionRecord.setDealType(DealType.COMMISSION);
            commissionRecordService.addComissionRecord(commissionRecord);

            //找当前用户A的上级用户B，判断团队返佣
            UserRecommenderDTO firstUserRecommenderDTO = userRecommenderMapper.selectUserRecommenderByUserId(commissionDTO.getUserId());
            if(firstUserRecommenderDTO != null) {
                if(BrokerLevel.DIAMOND.equals(firstUserRecommenderDTO.getLevel())) {
                    //如果上级B是钻石小精灵，则：
                    //1.当前订单放款额的0.5%返佣
                    commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(0.50));
                    //钻石团队佣金记录
                    CommissionRecord diamondTeamCommissionRecord = new CommissionRecord();
                    diamondTeamCommissionRecord.setUserId(firstUserRecommenderDTO.getRecommendUserId());
                    diamondTeamCommissionRecord.setOrderId(commissionDTO.getOrderId());
                    diamondTeamCommissionRecord.setAmount(commissionAmount);
                    diamondTeamCommissionRecord.setCreateTime(time);
                    dealRecordDTO.setCommissionRate(new BigDecimal(0.50));
                    dealRecordDTO.setBorkerLevelName("黄金会员");
                    diamondTeamCommissionRecord.setRemarkObject(dealRecordDTO);
                    diamondTeamCommissionRecord.setType(CommissionType.TEAM);
                    diamondTeamCommissionRecord.setDealType(DealType.TEAM);
                    diamondTeamCommissionRecord.setTeamUserId(commissionDTO.getUserId());
                    commissionRecordService.addComissionRecord(diamondTeamCommissionRecord);

                    //2.再找到上级B的上级C
                    UserRecommenderDTO secondUserRecommenderDTO = userRecommenderMapper.selectUserRecommenderByUserId(firstUserRecommenderDTO.getRecommendUserId());
                    if(secondUserRecommenderDTO != null) {
                        if(BrokerLevel.DIAMOND.equals(secondUserRecommenderDTO.getLevel())) {
                            //C如果是钻石，当前订单放款额的0.1%返佣给C，即钻石津贴
                            commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(0.10));
                            //钻石津贴佣金记录
                            CommissionRecord diamondAllowanceCommissionRecord = new CommissionRecord();
                            diamondAllowanceCommissionRecord.setUserId(secondUserRecommenderDTO.getRecommendUserId());
                            diamondAllowanceCommissionRecord.setOrderId(commissionDTO.getOrderId());
                            diamondAllowanceCommissionRecord.setAmount(commissionAmount);
                            diamondAllowanceCommissionRecord.setCreateTime(time);
                            dealRecordDTO.setCommissionRate(new BigDecimal(0.10));
                            dealRecordDTO.setUserRealName(firstUserRecommenderDTO.getRecommendUserRealName());
                            diamondAllowanceCommissionRecord.setRemarkObject(dealRecordDTO);
                            diamondAllowanceCommissionRecord.setType(CommissionType.DIAMOND_ALLOWANCE);
                            diamondAllowanceCommissionRecord.setDealType(DealType.DIAMOND_ALLOWANCE);
                            diamondAllowanceCommissionRecord.setTeamUserId(commissionDTO.getUserId());
                            commissionRecordService.addComissionRecord(diamondAllowanceCommissionRecord);
                        }
                    }
                }
            }
        }else if(BrokerLevel.DIAMOND.equals(commissionDTO.getBrokerLevel())) {
            //当前用户A是钻石小精灵
            //计算钻石小精灵的直推佣金
            commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(BrokerLevel.DIAMOND.getRewardRatio()));
            //钻石小精灵的直推佣金记录
            CommissionRecord commissionRecord = new CommissionRecord();
            commissionRecord.setUserId(commissionDTO.getUserId());
            commissionRecord.setOrderId(commissionDTO.getOrderId());
            commissionRecord.setAmount(commissionAmount);
            commissionRecord.setCreateTime(time);
            dealRecordDTO.setCommissionRate(new BigDecimal(BrokerLevel.DIAMOND.getRewardRatio()));
            commissionRecord.setRemarkObject(dealRecordDTO);
            commissionRecord.setType(CommissionType.BORKER_USER);
            commissionRecord.setDealType(DealType.COMMISSION);
            commissionRecordService.addComissionRecord(commissionRecord);

            //找当前用户A的上级用户B，没有团队返佣，直接返回钻石津贴，当前订单放款额的0.1%
            UserRecommenderDTO firstUserRecommenderDTO = userRecommenderMapper.selectUserRecommenderByUserId(commissionDTO.getUserId());
            if(firstUserRecommenderDTO != null) {
                commissionAmount = CommonUtils.multiplyWithPercent(loanAmount, new BigDecimal(0.10));
                //钻石津贴佣金记录
                CommissionRecord diamondAllowanceCommissionRecord = new CommissionRecord();
                diamondAllowanceCommissionRecord.setUserId(firstUserRecommenderDTO.getRecommendUserId());
                diamondAllowanceCommissionRecord.setOrderId(commissionDTO.getOrderId());
                diamondAllowanceCommissionRecord.setAmount(commissionAmount);
                diamondAllowanceCommissionRecord.setCreateTime(time);
                dealRecordDTO.setCommissionRate(new BigDecimal(0.10));
                diamondAllowanceCommissionRecord.setRemarkObject(dealRecordDTO);
                diamondAllowanceCommissionRecord.setType(CommissionType.DIAMOND_ALLOWANCE);
                diamondAllowanceCommissionRecord.setDealType(DealType.DIAMOND_ALLOWANCE);
                diamondAllowanceCommissionRecord.setTeamUserId(commissionDTO.getUserId());
                commissionRecordService.addComissionRecord(diamondAllowanceCommissionRecord);
            }
        }

    }
}
